<template>
  <!-- 拨打电话弹框 -->
  <div :class="'dial-number-wrap dialog-wrap ' +($Ctl.isCs(1)?'gradation-bg':'bg')">
    <!-- <div id="rong_video" style="height: 450px;width: 400px;background: #222222"></div> -->

    <div class="dialog-title">
      {{ state == 1 ? '正在与' : '呼叫'}}<span class="cell-username">{{ userName }}</span><span v-show="state == 1">{{ cellType == 1 ? '语音' : '视频' }}</span>
    </div>
    <!-- 通话屏幕 -->
    <div class="cell-screen">
      <!-- 呼叫中 -->
      <div class="celling" v-show="connectState == 0">
        <p class="celling-desc">正在与对方连接{{cellType == 1 ? '语音' : '视频'}}<span class="ani_dot">...</span></p>
        <div class="celling-pic">
          <img v-if="cellType == 2" :src="parames.headUrl || defaultUserHead">
          <i v-else class="iconfont icon_yuyin"></i>
        </div>
      </div>
      <div class="success-cell" v-show="connectState == 1">
        <!-- 视频通话中 -->
        <div class="videoing" v-show="cellType == 2">
          <div id="rong_video" style="height: 100%;width: 100%;"></div>
          <!-- 自己的视频 -->
          <div id="self_rong_video" class="self-video"></div>
        </div>
        <!-- 语音通话中 -->
        <div class="voiceing" v-show="cellType == 1">
          <ul class="left-ripple ripple-wrap">
            <li class="ripple-item ripple-one"></li>
            <li class="ripple-item ripple-two"></li>
            <li class="ripple-item ripple-three"></li>
          </ul>
          <div class="iconfont icon_yuyin"></div>
          <ul class="right-ripple ripple-wrap">
            <li class="ripple-item ripple-three"></li>
            <li class="ripple-item ripple-two"></li>
            <li class="ripple-item ripple-one"></li>
          </ul>
        </div>
        <!-- 时间统计 -->
        <div class="timing">{{ connectingTime }}</div>
      </div>
    </div>
    <!-- 底部按钮 -->
    <div class="cell-bottom-btns">
      <div class="cell-btn" @click="changeCellType(false)">
        <i class="cell-btn-icon iconfont change-cellType-btn" :class="{'iconweibiaoti-_shipin': cellType == 1, 'icon_yuyin': cellType == 2}"></i>
        <p class="cell-btn-text">切换为{{ cellType == 1 ? '视频' : '语音' }}</p>
      </div>
      <div class="cell-btn" @click="closeFun">
        <i class="cell-btn-icon iconfont icon_guaduan end-cell-btn"></i>
        <p class="cell-btn-text">结束</p>
      </div>
    </div>
  </div>
</template>
<script>
  import {getRongIMToken, callUser} from '@/api/api'
  import initIM from '@/libs/rongIM/im.js'
  import { setInterval, setTimeout } from 'timers'

  var hour = '00' // 时
  var minus = '00' // 分
  var seconds = '00' // 秒
  var x=0,a=0,b=0; // 计时器定义的变量


  var currentUser = {
    id: ''
  }
  /* 开始: IM 连接相关 */
  var imInstance = null
  var rongRTC = null
  var stream = null
  var rtcMessage = null
  // 聊天房间
  var room = null

  export default {
    props: {
      parames: {
        default () {
          return {}
        }
      }
    },
    data () {
      return {
        defaultUserHead: require('../../../assets/images/default/userHead.png'),
        state: 0, // 状态 0-呼叫中  1-通话中
        cellType: 2, // 呼叫方式 1-语音 2-视频
        userName: this.parames.name || '', // 呼叫的用户名称
        connectState: 0, // 连通话接状态 0-未连接  1-连接成功
        isPublish: false, // 发起者是否发布资源
        connectingTime: '00:00:00', // 连接时间计时
        roomId: this.$store.state.userInfo.accountName + '_' + this.parames.accountName + '_' + new Date().getTime(), //'90909090' 房间号：用户名+时间戳
        rongRTCParams: { // 连接融云服务的参数
            appkey: '3argexb63q8le', // appkey,
            token: ''
        },
        joinedUer: {},
        isSelfChange: false
      }
    },
    created () {
      let that = this
       /* 上次未断开，先断开 */
      if(imInstance) {
        this.leaveRoom()
        rongRTC = null
        stream = null
        room = null
        rtcMessage = null
      }

      that.$nextTick(() => {
        that.$Ctl.loading(0)
      })
      // 实例化
      that.initRongRTC()
      // 获取融云token
      that.getRongServerToken()

      window.FunList.changeCellType= that.changeCellType
    },
    methods: {
      // 切换通信方式
      changeCellType(paramType) {
        let that = this
        that.$Ctl.loading(1, 1000);
        if(!paramType || paramType != that.cellType) {
          // 禁用视频成功
          let user = {
            id: currentUser.id,
            stream: {
              type: rongRTC.StreamType.AUDIO_AND_VIDEO,
              tag: 'rtc'
            }
          }
          // {
          //   id: that.joinedUer.id,
          //   stream: {
          //     tag: that.joinedUer.stream.tag,
          //     type: rongRTC.StreamType.AUDIO_AND_VIDEO
          //   }
          // }
          if(paramType == 2 || that.cellType == 1) {
            // 启用视频
            stream.video.enable(user).then(function () {
                // 切换为视频
                that.cellType = 2
                console.log('启用视频成功');
            }, function (error) {
                console.log(error, '启用视频失败');
            })
          } else {
            // 禁用视频
            stream.video.disable(user).then(function () {
              console.log('禁用视频成功');
              // 切换为语音
              that.cellType = 1
            }, function (error) {
              console.log(error, '禁用视频失败');
            });
          }
        }
      },
      // 开始计时
      startTiming() {
        let that = this
        // 参数初始化
        x=0
        a=0
        b=0
        if(window.t1) {
          clearInterval(window.t1._id)
          window.t1 = null
        }

        window.t1 = setInterval(() => {
          that.runTime()
        }, 1000)
      },
      // 计时器算法
      runTime() {
        let that = this
        x++
        if(x<10){
          seconds = '0' + x;
        }else if(x >= 10 && x <= 59){
          seconds = x;
        }else if(x > 59){
          seconds = '00';
          x = 0;
          a++;
        }

        if(a < 10){
          minus = '0' + a;
        }else if(a >= 10 && a <= 59){
          minus = a;
        }else if(a > 59){
          minus = '00';
          a = 0;
          b++;
        }

        if(b<10){
          hour = '0' + b;
        }else if(b >=10 && b <= 59){
          hour = b;
        }

        that.connectingTime = hour+":"+minus+":"+seconds;
      },
      // 发起者关闭
      closeFun () {
        this.leaveRoom(() => {
          this.$emit('close')
        })
      },
      // 初始化通信参数
      initCellParames() {
        let that = this
        that.state = 0 // 状态 0-呼叫中  1-通话中
        that.cellType = 2 // 呼叫方式 1-语音 2-视频
        that.userName = '' // 呼叫的用户名称
        that.connectState = 0 // 连通话接状态 0-未连接  1-连接成功
        that.connectingTime = '00:00:00' // 连接时间计时
      },
      // 通知服务端发起通话
      cellNotice() {
        let that = this
        let param = {
          account: that.$store.state.userInfo.accountName || '', // 发起人
          targetUserAccount: that.parames.accountName || '', // 目标用户
          roomId: that.roomId	// 房间号
        }
        callUser(param).then(res => {
          if(res.status === 200) {
            console.log('通知服务端通话成功！')
          }
        })
      },
      // 实例化融云
      initRongRTC() {
        let that = this
        // 实例化rongRTC
        rongRTC = new RongRTC({
          RongIMLib: RongIMLib,
          error: function (error) {
            console.log(error);
          },
          logger: function (log) {
          }
        })
        // 创建聊天房间
        room = new rongRTC.Room({
          id: that.roomId,
          joined: function (user) {
            console.log(user.id + ' 加入房间');
          },
          left: function (user) {
            console.log(user.id + ' 离开房间');
            if(user.id != currentUser.id) {
              // 接收者关闭了视频
              document.querySelector('#rong_video').innerHTML = ''
              // 初始化通讯参数
              that.initCellParames()
              // 关闭
              that.closeFun()
            }
          }
        })
        // 实例化Stream
        stream = new rongRTC.Stream({
          published: function (user) {
            if(user.id != currentUser.id) {
              // 有新用户加入聊天房间。订阅该资源
              that.subscribeStream(user)
              that.joinedUer = user
              // 修改连接状态并开始计时
              that.connectState = 1
              that.startTiming()
            }
          },
          unpublished: function (user) {
            // 取消订阅
            user.stream.type = rongRTC.StreamType.AUDIO_AND_VIDEO;
            stream.unsubscribe(user);
            document.querySelector('#rong_video').innerHTML = ''
            // 关闭
            that.$emit('close')
          },
          muted: function (user) {
            console.log('muted', user);
          },
          unmuted: function (user) {
            console.log('unmuted', user);
          },
          disabled: function (user) {
            console.log('disabled', user);
            that.changeCellType(1);
          },
          enabled: function (user) {
            console.log('enabled', user);
            that.changeCellType(2);
          }
        });
        // 实例化消息
        rtcMessage = new rongRTC.Message({
          received: (res) => {
            // 将人员位置信息传送给控制台定位方法
            let positionInfo = res.content.content
            let personInfo = that.parames
            that.$Ctl.locateCallee(positionInfo, personInfo)
          }
        })
      },
      // 获取融云服务token
      getRongServerToken() {
        let that = this
        getRongIMToken().then(res => {
          if (res.status === 200) {
            that.rongRTCParams.token = res.data.token
            if (imInstance) {
              return
            }
            // 连接服务
            this.connect()
          }
        })
      },
      // 连接融云服务
      connect () {
        let that = this
        let callbacks = {
          connected: (instance, user) => {
            let userId = user.id
            currentUser.id = userId
            imInstance = instance
            console.log('连接成功，用户 ID: ' + userId)
            // 发起者先加入聊天房间
            that.joinRoom()
          },
          disconnectd: (status) => {
            imInstance = null
            if (status === 2) {
              console.log('退出聊天')
            } else {
              console.log('连接断开')
            }
          },
          error: () => {
            imInstance = null
            console.log('连接异常，状态码: ' + status)
          },
          onTokenIncorrect: () => {
            console.log('音视频信息获取异常： Token 不正确')
          }
        }
        initIM(that.rongRTCParams, callbacks)
      },
      // 发起者加入房间
      joinRoom () {
        let that = this
        room.join({
          id: currentUser.id
        }).then(function (user) {
          console.log('发起者加入房间成功')
          // 发起者发布资源
          setTimeout(() => {
            that.publish(user)
          }, 1000)
        }, function (error) {
          console.log('发起者加入房间失败：' + error)
        })
      },
      // 离开房间
      leaveRoom (callback) {
        let that = this
        room.leave().then(function (user) {
          function clearAll() {
              videoBox.innerHTML = '';
              removeMemberStreams();
              removeUsers();
          }
          console.log('发起者离开房间成功')
          that.disconnect(callback)
        }, function (error) {
          console.log('离开房间失败' + error)
        })
      },
      // 获取媒体流
      getMedia(callback) {
        let that = this
        stream.get().then(function ({mediaStream}) {
            callback(mediaStream);
            that.appendVideo({
              id: currentUser.id,
              stream: {
                  tag: 'rtc',
                  mediaStream: mediaStream
              }
            }, 'self_rong_video')
        }, function (error) {
            console.log(error, '获取媒体流失败:');
        });
      },
      // 发起者发布资源
      publish(user) {
        let that = this
        if (this.isPublish) {
          this.cellNotice()
          return console.log('资源已发布，无需重复发布');
        }
        this.isPublish = true;

        this.getMedia(function (mediaStream) {
            stream.publish({
              id: currentUser.id,
              stream: {
                type: rongRTC.StreamType.AUDIO_AND_VIDEO,
                tag: 'rtc',
                mediaStream: mediaStream
              }
            }).then(function () {
              console.log('发起者发布资源成功');
              that.cellNotice()
            }, function (error) {
                console.log(error, '发起者发布资源失败:');
            })
        });
      },
      // 有新用户加入房间，订阅资源
      subscribeStream(user) {
        let that = this
        user.stream.type = rongRTC.StreamType.AUDIO_AND_VIDEO;
        stream.subscribe(user).then(function (user) {
          console.log('订阅接受者资源成功');
          // 展示视频
          that.appendVideo(user, 'rong_video');
        }, function (error) {
        });
      },
      // 取消静音
      unmute(user) {
        stream.audio.unmute(user).then(function () {
            console.log('取消静音成功');
        }, function (error) {
            console.log(error, '取消静音失败');
        });
        ;
      },
      // 插入视频
      appendVideo(user, wrapId) {
        let that = this
        var videoBox = document.querySelector('#'+ wrapId);
        var createDiv = function (id, classList) {
            var node = document.createElement('div');
            node.id = id;
            node.classList = classList;
            return node;
        };
        var getId = function (user, suffix) {
            var id = user.id;
            var tag = user.stream.tag;
            var key = 'u_' + id + '_' + tag;
            if (suffix) {
              key += '_' + suffix;
            }
            return key;
        };

        var streams = user.stream;
        if (Object.prototype.toString.call(streams) != '[object Array]') {
            streams = [streams];
        }
        var ms = streams.filter(function (ms) {
            return ms.size != rongRTC.StreamSize.MIN;
        })[0];
        var mediaStream = ms.mediaStream;
        // Safari 下默认静音，否则无法自动播放
        if (navigator.appVersion.indexOf("Safari") > -1) {
            var tracks = mediaStream.getAudioTracks();
            tracks.forEach(function (track) {
                track.enabled = false;
            });
        }
        var video = function(stream) {
          var video = document.createElement('video');
          video.srcObject = stream;
          video.autoplay = true;
          return video;
        }(mediaStream) // createVideo(mediaStream);
        var userInfo = {
            id: user.id,
            stream: ms
        };
        if (user.id == currentUser.id) {
          video.muted = true;
        }
        var id = getId(userInfo);
        var box = createDiv(id, ['rong-video']);
        var childId = getId(userInfo, 'info');
        var child = createDiv(childId, ['rong-video-child'])
        box.appendChild(video);
        box.appendChild(child);
        videoBox.appendChild(box)

        that.$nextTick(() => {
          // 取消加入者的静音
          that.unmute(user)
        })
      },
      // 断开连接
      disconnect (callback) {
        if (!imInstance) {
          return
        }
        imInstance.disconnect()
        callback && callback()
      },
    }
  }
</script>

<style lang="scss">
  .dial-number-wrap {
    .cell-username {
      padding: 0 10px;
    }
    .cell-screen {
      margin-top: 25px;
      width: 100%;
      height: 62%;
      background: #000;
      .celling {
        padding-top: 50px;
        height: 100%;
        text-align: center;
        .celling-desc {
          color: #4095F0;
          font-size: 16px;
          .ani_dot {
            margin-left: 6px;
            display: inline-block;
            width: 1.5em;
            letter-spacing: 0.4em;
            vertical-align: bottom;
            overflow: hidden;
            animation: dot 3s infinite step-start;
          }
        }
        .celling-pic {
          margin-top: 20px;
          i {
            color: #3e3d3d;
            font-size: 80px;
          }
          img {
            width: 90px;
            height: 90px;
          }
        }
      }
      .success-cell {
        position: relative;
        width: 100%;
        height: 100%;
        .videoing {
          width: 100%;
          height: 100%;
          .rong-video {
            width: 100%;
            height: 100%;
            video {
              width: 100%;
              height: 100%;
            }
          }
          .self-video {
            position: absolute;
            top: 0;
            right: 0;
            height: 100px;
            width: 140px;
          }
        }
        .voiceing {
          display: flex;
          padding-top: 40px;
          justify-content: center;
          height: 100%;
          color: #258EF5;
          text-align: center;
          .ripple-wrap {
            display: flex;
            margin-top: 35px;
            width: 70px;
            height: 50px;
            justify-content: space-between;
            align-items: center;
            list-style: none;
            .ripple-item {
              width: 8px;
              height: 50px;
              background: #1a4e81;
            }
            .ripple-one {
              animation: ripple 1s ease-in-out 0s infinite;
            }
            .ripple-two {
              animation: ripple 1s ease-in-out .4s infinite;
            }
            .ripple-three {
              animation: ripple 1s ease-in-out .8s infinite;
            }
          }
          .iconfont {
            font-size: 100px;
          }
        }
        .timing {
          position: absolute;
          top: 70%;
          left: 0;
          width: 100%;
          margin-top: 30px;
          color: #258EF5;
          text-align: center;
        }
      }
    }
    .cell-bottom-btns {
      margin-top: 15px;
      display: flex;
      justify-content: center;
      width: 100%;
      .cell-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 200px;
        cursor: pointer;
        .cell-btn-icon {
          display: block;
          width: 54px;
          height: 54px;
          line-height: 46px;
          text-align: center;
          border-radius: 50%;
          font-size: 26px;
          color: #FFF;
          &.change-cellType-btn {
            border: 4px solid rgba(63,132,199,.3);
            background:rgba(63,132,199,1);
            background-clip: padding-box;
          }
          &.end-cell-btn {
            border: 4px solid rgba(151,59,53,.3);
            background:rgba(151,59,53,1);
            background-clip: padding-box;
          }
        }
        .cell-btn-text {
          margin-top: 6px;
          font-size: 14px;
          color:rgba(255,255,255,1);
        }
      }
    }
  }
</style>


